<template>
	<!-- <preview-images ref="previewImages" /> -->
	<!-- <div class="product-name">{{ productData.name }}</div> -->
	<el-card class="box-card" v-loading="loading">
		<slot name="header" slot="header"> </slot>
		<div class="box-card__body">
			<div class="cell">
				<span style="font-weight: 600">投保企业</span>
				<el-checkbox v-model="sameAsToubao" size="medium"
					>被保企业同投保企业
				</el-checkbox>
			</div>
			<el-form
				class="cell"
				:model="toubaoForm"
				:rules="rules"
				label-width="80px"
				ref="toubaoForm"
			>
				<el-form-item label="企业名称" prop="customerName" required>
					<el-select
						v-model="toubaoForm.customerName"
						@change="(val) => getToubaoById(val)"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择企业"
					>
						<el-option
							v-for="customer in customerOptions"
							:value="customer.customerId"
							:label="customer.customerName"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="联系人" prop="contactName" required>
					<el-input
						v-model="toubaoForm.contactName"
						size="mini"
						placeholder="请输入联系人"
						class="field"
					/>
				</el-form-item>

				<!-- <el-form-item label="手机号码" prop="contactPhone" required>
						<el-input
							v-model="toubaoForm.contactPhone"
							placeholder="请输入手机号码"
							size="mini"
							class="field"
						/>
					</el-form-item> -->

				<el-form-item label="详细地址" prop="address" required>
					<el-input
						v-model="toubaoForm.address"
						placeholder="请输入详细地址"
						size="mini"
						class="field"
					/>
				</el-form-item>
			</el-form>
			<div class="cell" v-if="sameAsToubao === false">
				<span style="font-weight: 600">被保企业</span>
			</div>
			<el-form
				v-if="sameAsToubao === false"
				class="cell"
				:model="beibaoForm"
				:rules="rules"
				label-width="80px"
				ref="beibaoForm"
			>
				<el-form-item label="企业名称" prop="customerName" required>
					<el-select
						v-model="beibaoForm.customerName"
						@change="(val) => getBeibaoById(val)"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择企业"
					>
						<el-option
							v-for="customer in customerOptions"
							:value="customer.customerId"
							:label="customer.customerName"
						/>
					</el-select>
				</el-form-item>
				<el-form-item
					label="行业大类"
					prop="premiumMode"
					v-if="productData.premiumMode"
				>
					<el-select
						v-model="beibaoForm.premiumMode"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择行业大类"
					>
						<el-option
							v-for="mode in productData.premiumMode"
							:value="mode.value"
							:label="mode.name"
							:key="mode.value"
						/>
					</el-select>
				</el-form-item>

				<el-form-item label="联系人" prop="contactName" required>
					<el-input
						v-model="beibaoForm.contactName"
						size="mini"
						placeholder="请输入联系人"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="手机号码" prop="contactPhone" required>
					<el-input
						v-model="beibaoForm.contactPhone"
						placeholder="请输入手机号码"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<el-form-item label="详细地址" prop="address" required>
					<el-input
						v-model="beibaoForm.address"
						placeholder="请输入详细地址"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<!-- <div style="grid-column: -1/1; text-align: center">
						<el-button size="small" type="primary" @click="saveBeibao">
							确认
						</el-button>
					</div> -->
			</el-form>
			<div class="cell">
				<span style="font-weight: 600">保障期限 </span>
			</div>
			<el-form
				class="cell"
				:model="qixianForm"
				:rules="qixianRules"
				label-width="80px"
				ref="qixianForm"
			>
				<el-form-item label="保单起期" prop="startTime" required>
					<el-date-picker
						v-model="qixianForm.startTime"
						size="mini"
						placeholder="请选择开始时间"
						type="date"
						value-format="yyyy-MM-dd"
						style="width: 100%"
						:picker-options="startDatePickerOptions"
					/>
					<span class="append-fix">00:00:00</span>
				</el-form-item>
				<el-form-item label="保单止期" prop="endTime" required>
					<el-date-picker
						v-model="qixianForm.endTime"
						readonly
						size="mini"
						placeholder="请选择结束时间"
						type="date"
						value-format="yyyy-MM-dd"
						style="width: 100%"
					/>
					<span class="append-fix">23:59:59</span>
				</el-form-item>
				<el-form-item label="保单期间" prop="endTime" required>
					<el-input
						v-model="baoxianqijian"
						readonly
						size="mini"
						style="width: 100%"
					>
					</el-input>
				</el-form-item>
				<!-- <div style="grid-column: -1/1; text-align: center">
						<el-button size="small" type="primary" @click="saveQixian">
							确 认
						</el-button>
					</div> -->
			</el-form>
			<div class="cell">
				<span style="font-weight: bold">项目信息</span>
			</div>
			<el-form
				class="cell"
				:model="baseForm"
				:rules="baseRules"
				label-width="80px"
				ref="baseForm"
			>
				<el-form-item
					label="屋面企业名称"
					prop="name"
					label-width="105px"
					required
				>
					<el-input
						v-model="baseForm.name"
						size="mini"
						style="width: 100%"
						placeholder="请输入屋面企业名称"
					>
					</el-input>
				</el-form-item>
				<el-form-item
					label="所属行业/工艺"
					prop="highRisk"
					label-width="152px"
					required
				>
					<el-select
						size="mini"
						placeholder="请选择行业/工艺"
						v-model="baseForm.highRisk"
						style="width: 100%"
					>
						<el-option
							v-for="option in highRiskOptions"
							:key="option"
							:label="option.split('-')[0]"
							:value="option"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="项目地址" prop="address" required>
					<xh-address
						:item="addressConfig"
						:value="baseForm.address"
						@value-change="onAddressChange"
						size="mini"
					></xh-address>
				</el-form-item>
				<el-form-item label="详细地址" prop="detailAddress" required>
					<el-input
						v-model="baseForm.detailAddress"
						placeholder="请输入项目详细地址"
						size="mini"
						style="width: 100%"
					>
					</el-input>
					<!-- <xh-address
							:item="addressConfig"
							:value="baseForm.address"
							@value-change="onAddressChange"
						></xh-address> -->
				</el-form-item>

				<el-form-item label="并网年份" prop="purchaseDate" required>
					<el-date-picker
						v-model="baseForm.purchaseDate"
						size="mini"
						placeholder="请选择并网年份"
						type="year"
						value-format="yyyy"
						style="width: 100%"
					/>
				</el-form-item>
				<el-form-item label="房屋结构" prop="type" required>
					<!-- 房屋结构 -->
					<el-select
						size="mini"
						placeholder="请选择房屋结构"
						v-model="baseForm.type"
						style="width: 100%"
					>
						<el-option
							v-for="option in typeOptions"
							:key="option"
							:label="option"
							:value="option"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					label="设计风载荷"
					prop="riskLevel"
					label-width="92px"
					:required="riskLevelRequired"
				>
					<el-select
						size="mini"
						placeholder="请选择设计风载荷"
						v-model="baseForm.riskLevel"
						style="width: 100%"
					>
						<el-option
							v-for="option in riskLevelOptions"
							:key="option"
							:label="option.split('-')[0]"
							:value="option"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="装机容量" prop="calculate" required>
					<el-select
						size="mini"
						placeholder="请选择装机容量"
						v-model="baseForm.calculate"
						style="width: 100%"
					>
						<el-option
							v-for="option in calculateOptions"
							:key="option"
							:label="option"
							:value="option"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					label="电站总投资额"
					prop="unit"
					label-width="105px"
					required
				>
					<el-input
						v-model="baseForm.unit"
						size="mini"
						placeholder="请输入电站总投资额"
						style="width: 100%"
					>
					</el-input>
				</el-form-item>
				<el-form-item
					label="第一受益人"
					prop="primaryBeneficiary"
					label-width="92px"
				>
					<el-input
						v-model="baseForm.primaryBeneficiary"
						size="mini"
						style="width: 100%"
						placeholder="请输入第一受益人"
					>
					</el-input>
				</el-form-item>
			</el-form>

			<div class="cell">
				<span style="font-weight: 600">投保方案 </span>
			</div>
			<el-form
				class="cell"
				style="grid-template-columns: 250px 260px"
				:model="riskForm"
				:rules="riskRules"
				ref="riskForm"
			>
				<el-form-item
					label="财产一切险保额"
					prop="allRisks"
					label-width="120px"
					required
				>
					<el-select
						size="mini"
						placeholder="是否投保"
						v-model="riskForm.allRisks"
						style="width: 100%"
					>
						<el-option label="投保" value="1"></el-option>
						<el-option label="不投保" value="2"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item prop="allRisksAmount" label-width="0">
					<el-input
						v-model="riskForm.allRisksAmount"
						placeholder="请填写数字，最高不超过本项目资产总额"
						size="mini"
					>
					</el-input>
				</el-form-item>
				<el-form-item
					label="公众责任险保额"
					prop="publicRisks"
					label-width="120px"
					required
				>
					<el-select
						size="mini"
						placeholder="是否投保"
						v-model="riskForm.publicRisks"
						style="width: 100%"
					>
						<el-option label="投保" value="1"></el-option>
						<el-option label="不投保" value="2"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item prop="publicRisksAmount" label-width="0">
					<el-select
						size="mini"
						placeholder="请选择保额"
						v-model="riskForm.publicRisksAmount"
						style="width: 100%"
					>
						<el-option
							label="累计300万，每次300万，每人每次100万"
							value="累计300万，每次300万，每人每次100万"
						></el-option>
						<el-option
							label="累计500万，每次500万，每人每次100万"
							value="累计500万，每次500万，每人每次100万"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					label="机器损坏险保额"
					prop="machineRisks"
					label-width="120px"
					required
				>
					<el-select
						size="mini"
						placeholder="是否投保"
						v-model="riskForm.machineRisks"
						style="width: 100%"
					>
						<el-option label="投保" value="1"></el-option>
						<el-option label="不投保" value="2"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item prop="machineRisksAmount" label-width="0">
					<el-input
						v-model="riskForm.machineRisksAmount"
						placeholder="请填写数字，最高不超过本项目设备价值总额"
						size="mini"
					>
					</el-input>
				</el-form-item>
			</el-form>
		</div>
		<slot name="footer" slot="footer"></slot>

		<!-- <div style="text-align: center">
			<el-button type="primary" @click="onInputEnd"
				>新增一个光伏项目投保</el-button
			>
		</div> -->
		<div class="readonly-mask" v-if="readonly"></div>
	</el-card>
</template>

<script>
import XhAddress from '@/components/createCom/XhAddress.vue'
import { customerList, customerById } from '@/api'
import { createPcOrder } from '../api/order'
import _ from 'lodash'
import * as REGEXP from '@/const/REGEXP'
import { downloadByResponse } from '@/utils/download'
import moment from 'moment'
var urlSearchParams = new URLSearchParams(location.search)
var UrlSearch = {}
for (let [key, value] of urlSearchParams.entries()) {
	UrlSearch[key] = value
}
import { transformKey } from '@/utils'
import { readonly } from 'vue'
// 高风险区名单
const dangeAreas = ['广东', '福建', '温州', '台州', '宁波', '舟山']
// 企业基本字段
const baoform = {
	customerName: '',
	certNum: '', // 统一代码
	address: '', // 详细地址
	contactName: '', // 联系人
	contactPhone: '', // 手机号
	businessLicense: '', // 营业执照
	code: '', // 验证码
	// provinceCode: '',
	cityCode: '',
	regionCode: '',
	// 产品订单的类型 1国寿类 2太保类
	policyType: 1 // 默认国寿类
}
export default {
	components: { XhAddress },
	props: {
		defaultToubao: {
			type: Object,
			default: () => ({})
		},
		defaultBeibao: {
			type: Object,
			default: () => ({})
		},
		defaultBase: {
			type: Object,
			default: () => ({})
		},
		defaultSameAs: {
			type: Boolean,
			default: true
		},
		defaultRisks: {
			type: Object,
			default: () => ({})
		},
		defaultQixian: {
			type: Object,
			default: () => ({})
		},
		businessId: [Number, String],
		readonly: Boolean
	},
	data() {
		var that = this
		var validatorForRisksAmount = (selectKey) => {
			return function (rule, value, callback) {
				if (that.riskForm[selectKey] == '1' && !value)
					callback('请输入正确的金额')
				else callback()
			}
		}
		const startTime = moment().add(1, 'days').format('yyyy-MM-DD')

		const riskLevelValidator = (rule, value, callback) => {
			if (
				this.riskLevelRequired && // 设计风载荷是否必填
				!value
			)
				callback(new Error('请选择设计风载荷'))
			else callback()
		}
		return {
			loading: false,
			productData: {},
			sameAsToubao: true, // 被保企业同投保企业
			businessId: '',
			toubaoForm: Object.assign({}, baoform, this.defaultToubao),
			beibaoForm: Object.assign({}, baoform, this.defaultBeibao),
			toubaoBusinessLicenseFile: null,
			beibaoBusinessLicenseFile: null,
			rules: {
				customerName: [{ required: true, message: '请选择企业' }],
				certNum: [{ required: true, message: '请输入统一社会信用代码' }],
				address: [{ required: true, message: '请输入详细地址' }],
				// provinceCode: [{ required: true, message: '请选择省份' }],
				cityCode: [{ required: true, message: '请选择地市' }],
				regionCode: [{ required: true, message: '请选择区县' }],
				contactName: [{ required: true, message: '请输入联系人' }],
				contactPhone: [{ required: true, message: '请输入联系方式' }],
				businessLicense: [{ required: true, message: '请上传营业执照' }],
				code: [{ required: true, message: '请输入短信验证码' }]
			},
			customerOptions: [],

			// 保障期限
			qixianForm: Object.assign(
				{
					startTime,
					endTime: ''
				},
				this.defaultQixian
			),
			qixianRules: {
				startTime: { required: true },
				endTime: { required: true }
			},
			qixianLoading: false,

			startDatePickerOptions: {
				disabledDate(date) {
					const start = new Date(startTime)
					return date.getTime() < start.getTime() - 24 * 3600000
				}
			},

			pickerOptions: {
				disabledDate(time) {
					const timeStramp = time.getTime()
					const { startTime, endTime } = that.qixianForm
					const minTime = new Date(startTime).getTime()
					const maxTime = new Date(endTime).getTime()
					return minTime > timeStramp && maxTime < timeStramp
				}
			},
			baseForm: Object.assign(
				{
					address: {}, // 项目地址
					detailAddress: '', // 详细地址
					name: '', // 屋面企业名称
					type: '', // 房屋机构
					calculate: '', // 装机容量
					highRisk: '', // 行业工艺
					purchaseDate: '', // 并网年份
					riskLevel: '', // 设计风载荷
					unit: '', // 电站总投资额
					primaryBeneficiary: '' // 第一受益人
				},
				this.defaultBase
			),
			baseRules: {
				name: [{ required: true, message: '请输入屋面企业名称' }],
				highRisk: [{ required: true, message: '请选择行业工艺' }],
				address: [{ required: true, message: '请选择项目地址' }],
				detailAddress: [{ required: true, message: '请输入详细地址' }],
				purchaseDate: [{ required: true, message: '请选择并网年份' }],
				type: [{ required: true, message: '请输入房屋机构' }],
				riskLevel: [{ validator: riskLevelValidator }],
				calculate: [{ required: true, message: '请输入装机容量' }],
				unit: [{ required: true, message: '请输入电站总投资额' }]
			},
			riskForm: Object.assign(
				{
					allRisks: '',
					allRisksAmount: '',
					publicRisks: '',
					publicRisksAmount: '',
					machineRisks: '',
					machineRisksAmount: ''
				},
				this.defaultRisks
			),
			riskRules: {
				allRisks: [{ required: true, message: '请输入' }],
				allRisksAmount: [
					{
						validator: validatorForRisksAmount('allRisks'),
						message: '请输入保额'
					}
				],
				publicRisks: [{ required: true, message: '请输入' }],
				publicRisksAmount: [
					{
						validator: validatorForRisksAmount('publicRisks'),
						message: '请选择保额'
					}
				],
				machineRisks: [{ required: true, message: '请输入' }],
				machineRisksAmount: [
					{
						validator: validatorForRisksAmount('machineRisks'),
						message: '请输入保额'
					}
				]
			},
			// 行业字典
			highRiskOptions: [
				'纺织业、纺织服装、鞋、帽制造业-1.1',
				'印刷业-1.1',
				'化学纤维制造业-1.1',
				'化学原料及化学制品制造业-1.1',
				'金属冶炼及压延加工业-1.1',
				'食品加工行业-1.1',
				'医药制造业-1.2',
				'皮革毛皮羽毛及其制品业-1.2',
				'文教体育用品制造业-1.2',
				'橡胶制造业-1.2',
				'仓储物流-1.2',
				'注塑行业-1.2',
				'光伏电站下方企业为海绵、泡棉、发泡类生产或仓储-拒保',
				'木制、海绵家具的生产及仓储-拒保',
				'电池生产及仓储-拒保',
				'电镀工艺-拒保',
				'含易燃易爆工艺-拒保',
				'其他-1'
			],
			// 房屋结构
			typeOptions: ['钢结构', '钢混结构', '砖瓦结构', '其他'],
			// 装机容量字典
			calculateOptions: [
				'装机容量≤0.5MW',
				'0.5MW＜装机容量≤1MW',
				'1MW＜装机容量≤2MW',
				'2MW＜装机容量≤3MW',
				'3MW＜装机容量≤4MW',
				'4MW＜装机容量'
			],
			riskLevelOptions: [
				'台风区设计风荷载取值:25年一遇-1',
				'台风区设计风荷载取值:50年一遇-0.6',
				'台风区无法提供设计文件或风荷载-拒保',
				'非台风区提供设计文件及设计风荷载-0.9'
			],
			addressConfig: {}
		}
	},
	computed: {
		productId() {
			return 11837
		},
		baoxianqijian() {
			var { startTime, endTime } = this.qixianForm
			if (startTime && endTime) {
				var diffTime =
					new Date(endTime).getTime() - new Date(startTime).getTime()
				return Math.floor(diffTime / 1000 / 60 / 60 / 24) + 1
			} else {
				return '--'
			}
		},
		// 设计风载荷是否必填
		riskLevelRequired() {
			return Object.values(this.baseForm.address).some((str) =>
				dangeAreas.find((area) => str.includes(area))
			)
		}
	},
	async created() {
		this.fetchCustomerOptions()
		this.sameAsToubao = this.defaultSameAs
	},
	watch: {
		'qixianForm.startTime': {
			handler(val) {
				this.qixianForm.endTime = moment(this.qixianForm.startTime)
					.add(1, 'years')
					.subtract(1, 'days')
					.format('yyyy-MM-DD')
			},
			immediate: true
		}
	},
	methods: {
		// 获取企业选项列表
		fetchCustomerOptions() {
			customerList().then((res) => {
				this.customerOptions = res.data
			})
		},
		// 地址选择回调
		onAddressChange(data) {
			this.baseForm.address = data.value
		},
		getBeibaoById(id, type) {
			customerById(id).then((res) => {
				const tempForm = this.beibaoForm
				for (let key in res.data) {
					tempForm[key] = res.data[key]
				}
			})
		},
		getToubaoById(id) {
			customerById(id).then((res) => {
				const tempForm = this.toubaoForm
				for (let key in res.data) {
					tempForm[key] = res.data[key]
				}
			})
		},
		validate() {
			return Promise.all([
				this.$refs.toubaoForm.validate(),
				this.$refs.beibaoForm?.validate(),
				this.$refs.qixianForm.validate(),
				this.$refs.baseForm.validate(),
				this.$refs.riskForm.validate()
			]).then(() => {
				const {
					toubaoForm,
					beibaoForm,
					qixianForm,
					baseForm,
					riskForm,
					sameAsToubao
				} = this
				return {
					toubaoForm,
					beibaoForm,
					qixianForm,
					baseForm,
					riskForm,
					sameAsToubao
				}
			})
		},
		onPreview(url) {
			this.$refs.previewImages.open(url)
		},
		resetFields() {
			this.$refs.toubaoForm.resetFields()
			this.$refs.beibaoForm?.resetFields()
			this.$refs.baseForm.resetFields()
			this.$refs.riskForm.resetFields()

			setTimeout(() => {
				this.$refs.baseForm.clearValidate('address')
			}, 100)
		}
	}
}
</script>

<style lang="scss" scoped="scoped">
.box-card {
	transition: all 0.4s ease-in;
	&__body {
		display: grid;
		grid-template-columns: 180px 1fr;
		gap: 1px;
		background-color: #e8e8e8;

		.cell {
			background-color: #fff;
			padding: 12px;
			display: grid;
			align-items: center;
		}
	}

	&.cardHideUp {
		transform: scale(1, 0);
		opacity: 0;
	}
}
.product-name {
	font-size: 20px;
	font-weight: 600;
	text-align: center;
	margin-block: 20px;
}
::v-deep {
	.el-card__body {
		position: relative;
	}
	.el-form {
		display: grid;
		gap: 15px;
		grid-template-columns: 1fr 1fr;
	}
	.el-form-item {
		margin-bottom: 0;
	}

	.el-table__header tr th {
		font-size: 13px;
		color: #333;
		background: #fbfcff;
	}
	._error_ {
		color: #f22 !important;
	}
}
.field {
	width: 100%;
}
.append-fix {
	position: absolute;
	right: 1em;
	top: 50%;
	transform: translateY(-50%);
	color: #999;
}
.hide-upload-button ::v-deep .el-upload--picture-card {
	display: none;
}
.readonly-mask {
	position: absolute;
	right: 0;
	left: 0;
	top: 0;
	bottom: 0;
	z-index: 1;
}
</style>
